package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.Constant;

import util.KeyGen;
import util.MyJson;
import dao.UserDao;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw = response.getWriter();
		String email = request.getParameter("email");
		String pwd = request.getParameter("pwd");
		if (null == email || "".equals(email.trim()))
			pw.write(MyJson.toJson("msg","请输入正确的email 地址，谢谢！"));
		else if (null == pwd || "".equals(pwd.trim()))
			pw.write(MyJson.toJson("msg",new String("您输入的密码不能为空，谢谢！")));
		else if (email.length() > 100) {
			pw.write(MyJson.toJson("msg","您输入的email:" + email + " 地址太长啦，肯定不正确，谢谢！"));
		} else {
			UserDao userDao =new UserDao();
			int n=userDao.login(email,pwd);
			System.out.println("n=="+n);
			if (n>0){
				//登录成功 n 则为uid
				String key=KeyGen.getKey(n);
				pw.write(MyJson.toJson("msg","0"));	//	
				
				Cookie cookie=new Cookie("user", key);
				cookie.setMaxAge(Constant.CookieExpired);
				cookie.setPath("/");
				response.addCookie(cookie);				
			}
			else if (-403==n)
				pw.write(MyJson.toJson("msg","密码错误！"));
			else if (-404==n){
				pw.write(MyJson.toJson("msg","用户"+email+"不存在！"));
			}
			else if(-500==n)
				pw.write(MyJson.toJson("msg","系统错误，请稍后再试！"));
			
		}
		pw.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}
